package com.aduerr.v1shouyin.mvp.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.*;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.aduerr.v1shouyin.App;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.Constants;
import com.aduerr.v1shouyin.entity.MemberAddBalanceEntity;
import com.aduerr.v1shouyin.entity.MemberInfoEntity;
import com.aduerr.v1shouyin.entity.MemberRechargeAndConsumeEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.util.LogUtils;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.aduerr.v1shouyin.view.SecurityCodeView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.internal.observers.BlockingBaseObserver;
import io.reactivex.schedulers.Schedulers;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.HashMap;


public class MemberInchargSeconActivity extends AppCompatActivity {

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.et_incharg)
    EditText etIncharg;
    @BindView(R.id.tv_cal_saoma_pay_member)
    TextView tvCalSaomaPayMember;
    @BindView(R.id.tv_cal_xianjin_shoukuan_member)
    TextView tvCalXianjinShoukuanMember;
    //=================================================输入密码的控件
    Dialog dialog;
    SecurityCodeView securityCodeView;
    private String scanMemberNo;
    private String inchargemoney;
    private MemberInfoEntity.DataBean memberInfoEntity;
    private String beizhu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_member_incharg_secon);
        ButterKnife.bind(this);
        initUI();
        initDate();
    }

    private void initDate() {
        Intent intent = getIntent();
        if(intent != null) {
            beizhu = getIntent().getStringExtra("beizhu");
            scanMemberNo = getIntent().getStringExtra(Constants.SCANMEMBERNO);
            memberInfoEntity =
                    (MemberInfoEntity.DataBean) getIntent().getSerializableExtra(
                            "beformemberincahrgeinfo");
            intent.putExtra(Constants.SCANMEMBERNO, scanMemberNo);
        }

    }

    private void initUI() {
        tvTitle.setText("会员充值");
    }

    @OnClick({R.id.img_back, R.id.tv_cal_saoma_pay_member,
            R.id.tv_cal_xianjin_shoukuan_member})
    public void onViewClicked(View view) {
        switch(view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.tv_cal_saoma_pay_member:
                inchargemoney = etIncharg.getText().toString();
                if(TextUtils.isEmpty(inchargemoney)) {
                    ToastUtils.showToast(MemberInchargSeconActivity.this, "充值金额不能为空");
                    return;
                }

                toDialogActivity(0);
                break;
            case R.id.tv_cal_xianjin_shoukuan_member:
                inchargemoney = etIncharg.getText().toString();
                if(TextUtils.isEmpty(inchargemoney)) {
                    ToastUtils.showToast(MemberInchargSeconActivity.this, "充值金额不能为空");
                    return;
                }
                toDialogActivity(1);
                break;
        }
    }

    private void toDialogActivity(int type) {
        View view =
                LayoutInflater.from(MemberInchargSeconActivity.this).inflate(R.layout.dialog_tuikuan, null);
        // 对话框
        dialog = new Dialog(MemberInchargSeconActivity.this);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.show();
        // 设置宽度为屏幕的宽度
        WindowManager windowManager = this.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); // 设置宽度
        dialog.getWindow().setAttributes(lp);
        dialog.getWindow().setContentView(view);
        //==================================弹出键盘================================================================
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        //===========================================================================================================
//        InputTools.KeyBoard(et_hexiao, "open");
//        InputTools.HideKeyboard(et_hexiao);
        //findview
        //找到自定义的控件用来显示密码
        securityCodeView = (SecurityCodeView) view.findViewById(R.id.scv_edittext);
        TextView title = (TextView) view.findViewById(R.id.dialogui_tv_title);
        title.setText("充值密码");
        securityCodeView.setInputCompleteListener(new SecurityCodeView.InputCompleteListener() {
            @Override
            public void inputComplete() {
                dialog.hide();
                LogUtils.e("getEditContent", securityCodeView.getEditContent());
                if(type == 0) {
                    toMemberAddBalance(scanMemberNo, securityCodeView.getEditContent());
                } else {
                    toCashMoneymember(scanMemberNo, securityCodeView.getEditContent());
                }

//                getPresenter().toTuikuan(MemberInchargActivity.this, securityCodeView
//                .getEditContent(), orderid_content, handinputmoney);

            }

            @Override
            public void deleteContent(boolean isDelete) {
                //DO NO THING
            }
        });
    }

    //扫码支付
    private void toMemberAddBalance(String scanMemberNo, String operatePass) {
        if(TextUtils.isEmpty(inchargemoney)) return;
        if(TextUtils.isEmpty(scanMemberNo)) return;
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("scanMemberNo", scanMemberNo);
        addParams.put("payMoney", inchargemoney);
        addParams.put("operatePass", operatePass);
        addParams.put("bz", beizhu + "");
        APIRetrofit.getAPIService().memberAddBalance(RXRequest.getXingPosParams(addParams, MemberInchargSeconActivity.this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<MemberAddBalanceEntity>() {
                    @Override
                    public void onNext(MemberAddBalanceEntity memberAddBalanceEntity) {
                        int success = memberAddBalanceEntity.getSuccess();
                        if(success == 1) {
                            Intent intent = new Intent(MemberInchargSeconActivity.this,
                                    ScanningActivity.class);
                            intent.putExtra(Constants.QRCODE_CAPUTER,
                                    Constants.MEMBER_SCANCODECOLLECTION_QR);
                            intent.putExtra(Constants.REALMONEY, inchargemoney);
                            intent.putExtra("beizhu", beizhu);
                            //默认自定义赠送金额是0元
                            intent.putExtra("sendmoney", "0");
                            intent.putExtra("scanMemberNo", scanMemberNo);
                            if(memberInfoEntity != null) {
                                intent.putExtra("beformemberincahrgeinfo",
                                        memberInfoEntity);
                            }
                            intent.putExtra(Constants.FROMORDERID,
                                    memberAddBalanceEntity.getData().getOrderid());
                            startActivity(intent);
                            finish();
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            SharedPreferencesUtils.remove(MemberInchargSeconActivity.this, "autologin");
                            SharedPreferencesUtils.remove(MemberInchargSeconActivity.this, "remberpassword");
                            startActivity(new Intent(MemberInchargSeconActivity.this,
                                    BangGuidActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(memberAddBalanceEntity.getErrMsg());
                            SharedPreferencesUtils.remove(MemberInchargSeconActivity.this, "autologin");
                            SharedPreferencesUtils.remove(MemberInchargSeconActivity.this, "remberpassword");
                            startActivity(new Intent(MemberInchargSeconActivity.this,
                                    LoginActivity.class));
                            finish();
                        } else if(success == -3) {//充值密码错误
                            ToastUtils.showToast(MemberInchargSeconActivity.this,
                                    memberAddBalanceEntity.getErrMsg() + "");
                        } else {
                            ToastUtils.showToast(MemberInchargSeconActivity.this,
                                    memberAddBalanceEntity.getErrMsg() + "");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(App.getApp(), "网络连接超时", Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(App.getApp(), "连接失败", Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(App.getApp(), "检查网络状态", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    //现金支付
    private void toCashMoneymember(String erWeiMaResult, String operatePass) {
        if(TextUtils.isEmpty(inchargemoney)) return;
        if(TextUtils.isEmpty(erWeiMaResult)) return;
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("scanMemberNo", erWeiMaResult);
        addParams.put("payMoney", inchargemoney);
        addParams.put("operatePass", operatePass);
        addParams.put("bz", beizhu + "");
        APIRetrofit.getAPIService().memberToPayAndConsume(RXRequest.getXingPosParams(addParams, MemberInchargSeconActivity.this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<MemberRechargeAndConsumeEntity>() {
                    @Override
                    public void onNext(MemberRechargeAndConsumeEntity memberRechargeAndConsumeEntity) {
                        int success = memberRechargeAndConsumeEntity.getSuccess();
                        if(success == 1) {
                            MemberRechargeAndConsumeEntity.DataBean data =
                                    memberRechargeAndConsumeEntity.getData();
                            if(data != null) {
                                //// TODO: 2017/12/12 0012  充值成功
                                Intent intent =
                                        new Intent(MemberInchargSeconActivity.this,
                                                ResultActivity.class);
                                intent.putExtra("money", inchargemoney);
                                intent.putExtra("sucess", "3");
                                intent.putExtra("beizhu", beizhu);
                                intent.putExtra("sendmoney", "0");
                                intent.putExtra("paytype", "现金付款");
                                intent.putExtra("aftermemberincahrgeinfo", data);
                                if(memberInfoEntity != null) {
                                    intent.putExtra("beformemberincahrgeinfo",
                                            memberInfoEntity);
                                }
                                startActivity(intent);
                                finish();
                            } else {

                            }
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            SharedPreferencesUtils.remove(MemberInchargSeconActivity.this, "autologin");
                            SharedPreferencesUtils.remove(MemberInchargSeconActivity.this, "remberpassword");
                            startActivity(new Intent(MemberInchargSeconActivity.this,
                                    BangGuidActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(memberRechargeAndConsumeEntity.getErrMsg());
                            SharedPreferencesUtils.remove(MemberInchargSeconActivity.this, "autologin");
                            SharedPreferencesUtils.remove(MemberInchargSeconActivity.this, "remberpassword");
                            //// TODO: 2017/12/9 0009 去登录的界面
                            startActivity(new Intent(MemberInchargSeconActivity.this,
                                    LoginActivity.class));
                            finish();
                        } else if(success == -3) {//充值密码错误
                            ToastUtils.showToast(MemberInchargSeconActivity.this,
                                    memberRechargeAndConsumeEntity.getErrMsg() + "");
                        } else {//跳转到结果的界面
                            ToastUtils.showToast(MemberInchargSeconActivity.this,
                                    memberRechargeAndConsumeEntity.getErrMsg() + "");
//                            Intent intent = new Intent(MemberInchargSeconActivity
//                            .this, ResultActivity.class);
//                            intent.putExtra("money", inchargemoney);
//                            intent.putExtra("sucess", "4");
//                            startActivity(intent);
//                            finish();
                        }


//                        ToastUtils.showToast(context, memberRechargeAndConsumeEntity
//                        .getData().getBalance());
//                        Intent intent = new Intent(context, PayStateActivity.class);
//                        Bundle bundle = new Bundle();
//                        bundle.putSerializable(Constants
//                        .MEMBERRECHARGEANDCONSUMEENTITY,
//                        memberRechargeAndConsumeEntity);
//                        intent.putExtras(bundle);
//                        intent.putExtra(Constants.GOTO_PAYSTATE_TYPE, Constants
//                        .MEMBER_PAYMENT_TO_STATE);
//                        intent.putExtra(Constants.REALMONEY, payMoney);
//                        intent.putExtra(Constants.PAYSTATE, true);
//                        startActivity(intent);
//                        finish();
                    }

                    @Override
                    public void onError(Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(App.getApp(), "网络连接超时", Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(App.getApp(), "连接失败", Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(App.getApp(), "检查网络状态", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

}
